package com.example.rbacmanage.controller.background;

import cn.hutool.core.date.DateUtil;
import com.example.rbacmanage.common.Result;
import com.example.rbacmanage.entity.app.AppMenu;
import com.example.rbacmanage.entity.app.MenuOrder;
import com.example.rbacmanage.entity.app.MinAppConfig;
import com.example.rbacmanage.property.DefinedProperty;
import com.example.rbacmanage.service.app.AppMenuService;
import com.example.rbacmanage.service.app.MenuOrderService;
import com.example.rbacmanage.service.app.MinAppConfigService;
import com.example.rbacmanage.util.WxUtil;
import com.wechat.pay.java.service.payments.model.Transaction;
import com.wechat.pay.java.service.payments.model.TransactionPayer;
import com.wechat.pay.java.service.refund.model.Refund;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.graphql.GraphQlTest;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;

@RestController
@RequestMapping("/background/menuorder")
public class MenuOrderController {
    @Autowired
    private MenuOrderService menuOrderService;
    @Autowired
    private AppMenuService appMenuService;
    @Autowired
    private MinAppConfigService minAppConfigService;
    @Autowired
    private DefinedProperty definedProperty;

    @GetMapping("/page")
    public Result page(MenuOrder menuOrder){
        return Result.success(menuOrderService.getPage(menuOrder));
    }

    @PreAuthorize("hasAnyAuthority('background:menuorder:update')")
    @PutMapping("/update")
    public Result update(@RequestBody MenuOrder menuOrder){
        menuOrderService.update(menuOrder);
        return Result.success();
    }

    @PreAuthorize("hasAnyAuthority('background:menuorder:refund')")
    @GetMapping("/refund")
    public Result refund(MenuOrder order){
        MenuOrder menuOrder = menuOrderService.getById(order.getId());
        if (menuOrder != null) {
            AppMenu menu = appMenuService.getById(menuOrder.getMenuId());
            if (menu != null && menu.getShopId() != null) {
                MinAppConfig minAppConfig = minAppConfigService.getOneByShopIdAndType(menu.getShopId(), "0");
                if (minAppConfig != null) {
                    minAppConfig.setPrivateKeyPath(minAppConfig.getPrivateKeyPath().replace("/profile/",definedProperty.getUploadProfile()));
                    minAppConfig.setPublicKeyPath(minAppConfig.getPublicKeyPath().replace("/profile/",definedProperty.getUploadProfile()));
                    Refund refund = WxUtil.refundOrder(minAppConfig.getMerchantId(),
                            minAppConfig.getPrivateKeyPath(),minAppConfig.getPublicKeyPath(),minAppConfig.getMerchantSerialNumber()
                            ,minAppConfig.getApiV3Key(),menuOrder.getOutTradeNo(),minAppConfig.getPublicKeyId(),menuOrder.getId());
                    if (refund != null) {
                        order.setRefundId(refund.getRefundId());
                        order.setOutRefundNo(refund.getOutRefundNo());
                        if (refund.getChannel() != null){
                            order.setChannel(refund.getChannel().name());
                        }
                        order.setUserReceivedAccount(refund.getUserReceivedAccount());
                        if (refund.getSuccessTime() != null) {
                            order.setRefundSuccessTime(DateUtil.parse(refund.getSuccessTime()));
                        }
                        order.setRefundCreateTime(DateUtil.parse(refund.getCreateTime()));
                        order.setRefundStatus(refund.getStatus().name());
                        if (refund.getFundsAccount() != null) {
                            order.setFundsAccount(refund.getFundsAccount().name());
                        }
                        if (refund.getAmount() != null) {
                            order.setRefundAmount(BigDecimal.valueOf(refund.getAmount().getRefund()));
                        }
                    }
                }
            }
            menuOrderService.update(order);
        }
        return Result.success();
    }


    /**
     * 退款回调
     * @param menuOrderId
     * @return
     */
    @PostMapping("/refund_notify_url/{menuOrderId}/{outTradeNo}")
    public Result refund_notify_url(@PathVariable("menuOrderId") Long menuOrderId,@PathVariable("outTradeNo")String outTradeNo){
        MenuOrder menuOrder = menuOrderService.getById(menuOrderId);
        if (menuOrder != null) {
            menuOrder.setOrderStatus("1");
            menuOrder.setOutTradeNo(outTradeNo);
            AppMenu menu = appMenuService.getById(menuOrder.getMenuId());
            if (menu != null && menu.getShopId() != null) {
                MinAppConfig minAppConfig = minAppConfigService.getOneByShopIdAndType(menu.getShopId(), "0");
                if (minAppConfig != null) {
                    minAppConfig.setPrivateKeyPath(minAppConfig.getPrivateKeyPath().replace("/profile/",definedProperty.getUploadProfile()));
                    minAppConfig.setPublicKeyPath(minAppConfig.getPublicKeyPath().replace("/profile/",definedProperty.getUploadProfile()));
                    Refund refund = WxUtil.queryRefundOrder(minAppConfig.getMerchantId(),
                            minAppConfig.getPrivateKeyPath(),minAppConfig.getPublicKeyPath(),minAppConfig.getMerchantSerialNumber()
                            ,minAppConfig.getApiV3Key(),outTradeNo,minAppConfig.getPublicKeyId());
                    if (refund != null) {
                        if (refund.getSuccessTime() != null) {
                            menuOrder.setRefundSuccessTime(DateUtil.parse(refund.getSuccessTime()));
                        }
                        menuOrder.setRefundStatus(refund.getStatus().name());
                        menuOrder.setOrderStatus("5");
                    }
                }
            }
            menuOrderService.update(menuOrder);
        }
        return Result.success();
    }
}
